﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Media;
using System.Text;
using System.Web.UI;
using Google.Translates.Core;

namespace ml_test_google_trans.TTS
{
    public partial class SimpleSpeech : Page
    {
        private const string PLAYER_TYPE_WINDOW_MEDIA_PLAYER = "WmPlayer", PLAYER_TYPE_QUICKTIME_PLAYER = "QtPlayer", TTS_TYPE_GOOGLE="GoogleTTS", TTS_TYPE_BING="BingTTS";

        public string BAES_DIR_PATH
        {
            get
            {
                return Server.MapPath("/TTS/SoundFiles");
            }
        }

        private void SetPageControls()
        {
            if (Directory.Exists(BAES_DIR_PATH) && Directory.GetFiles(BAES_DIR_PATH).Length > 0)
            {
                var sbMsg = new StringBuilder();
                foreach (var f in Directory.GetFiles(BAES_DIR_PATH))
                {
                    if (f.ToLower().EndsWith(".mp3"))
                    {
                        var txtPath = f.Substring(0, f.Length - 4) + ".txt";
                        var fileShotName = f.Substring(f.LastIndexOf("\\") + 1);
                        var sr = new StreamReader(txtPath);
                        var itemContext = "";
                        try
                        {
                            if (sr.Peek() > 0)
                                itemContext = Server.UrlDecode(sr.ReadLine());
                        }
                        finally
                        {
                            sr.Dispose();
                            sr.Close();
                        }

                        sbMsg.Append("<br />SpeechFile [  <B><I>" + fileShotName + "</I></B>  ] means [  <B><U>" + itemContext + "</U></B>  ]<br />");
                    }
                }
                btnPlaySound.Enabled = sbMsg.Length > 0;
                lblContext.Text = sbMsg.ToString();
            }
            else
                btnPlaySound.Enabled = false;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                rblPlayMode.Items.Add(PLAYER_TYPE_WINDOW_MEDIA_PLAYER);
                rblPlayMode.Items.Add(PLAYER_TYPE_QUICKTIME_PLAYER);
                rblPlayMode.SelectedIndex = 0;
                rblTtsType.Items.Add(TTS_TYPE_GOOGLE);
                rblTtsType.Items.Add(TTS_TYPE_BING);
                rblTtsType.SelectedIndex = 0;
                SetPageControls();
            }
                
        }

        public string GetPlayTheSpeechFileScript(string fileName, ref int timeIntrerval, string playerTypeName, int timeDelay)
        {
            var reVal = new StringBuilder();

            string filePath = BAES_DIR_PATH + "\\" + fileName;
            if (!File.Exists(filePath)) return null;
            if (fileName.LastIndexOf("_") < 0) return null;
            var tempStartIndex = fileName.LastIndexOf("_") + 1;
            if (fileName.Length - 4 - tempStartIndex < 1) return null;
            var tempIndex = Convert.ToInt32(fileName.Substring(tempStartIndex, fileName.Length - 4 - tempStartIndex));
            var bitVal = Convert.ToInt32(fileName.Substring(0, fileName.LastIndexOf("_"))); ;
            reVal.Append("var sh"+tempIndex+" = setInterval(function(){");
            if(playerTypeName == PLAYER_TYPE_WINDOW_MEDIA_PLAYER)
                reVal.Append("document.getElementById(\"Player"+fileName.Substring(0,fileName.Length-4)+ "\").controls.Play();");
            else
                reVal.Append("document.getElementById(\"Player"+fileName.Substring(0,fileName.Length-4)+ "\").Play();" );
            if (tempIndex > 0)
                reVal.Append("clearInterval(sh" + (tempIndex - 1) + ");");
            reVal.Append("}, " + timeIntrerval + ");\r\n");
            var fi = new FileInfo(filePath);
            
            long eachTime = (fi.Length * 1000 * 8 / (bitVal * 1024));//计算MP3播放的时间
            eachTime += timeDelay;//是否需要延时,在QuickTime Player加载时,需要
            timeIntrerval += (int)eachTime;
            return reVal.ToString();
        }

        protected void btnSaveSpeechFile_Click(object sender, EventArgs e)
        {
            DateTime startDate = DateTime.Now;
            if (txtTrg.Text.Length > 0)
            {
                var fNames = new StringCollection();
                if(Directory.Exists(BAES_DIR_PATH)) Directory.Delete(BAES_DIR_PATH, true);
                Directory.CreateDirectory(BAES_DIR_PATH);
                string msg = "";
                var trglangKey = ddlTo.SelectedValue;
               
                
                if(rblTtsType.SelectedValue == TTS_TYPE_GOOGLE)
                {
                    trglangKey = trglangKey == "zh-CN" ? "zh-CHS" : trglangKey;
                    trglangKey = trglangKey == "zh-TW" ? "zh-CHT" : trglangKey;
                    msg = new SpeechByGoogleHttp().SaveSpeechFiles(txtTrg.Text, trglangKey,BAES_DIR_PATH, ref fNames);
                }
                else if(rblTtsType.SelectedValue == TTS_TYPE_BING)
                    msg = new SpeechByBingHttp().SaveSpeechFiles(txtTrg.Text, trglangKey ,BAES_DIR_PATH, ref fNames);
                lblMsg.Text = msg;
                lblMsg.Text += "\r\n\r\nUses Time : [" + (DateTime.Now - startDate).TotalMilliseconds + "]ms";
                SetPageControls();
            }
        }

        protected void SetSpeechByScript(string[] fileNames,string playerTypeName)
        {
            var sbObjScript = new StringBuilder();
            var sbScript = new StringBuilder("<script type=\"text/javascript\">\r\n");
            int timeIntev = 0;
            
            
            int amount = 0;
            foreach (string fName in fileNames)
            {
                int timeDelay = 0;
                string fileName = fName.Substring(fName.LastIndexOf('\\') + 1);
                if (!fileName.ToLower().EndsWith(".mp3")) continue;

                if(playerTypeName == PLAYER_TYPE_WINDOW_MEDIA_PLAYER)
                {
                    sbObjScript.Append("<object style=\"width: 0; height: 0;\" id=\"Player" + fileName.Substring(0, fileName.Length - 4) + "\" classid=\"CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6\" type=\"application/x-oleobject\">\r\n");
                    sbObjScript.Append("<param name=\"URL\" value=\"SoundFiles/" + fileName + "\">\r\n<param name=\"autoStart\" value=\"false\"></object>\r\n");
                }
                else if(playerTypeName == PLAYER_TYPE_QUICKTIME_PLAYER)
                {
                    sbObjScript.Append("<object id=\"Player" + fileName.Substring(0, fileName.Length - 4) + "\" classid=\"clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B\" codebase=\"http://www.apple.com/qtactivex/qtplugin.cab\">\r\n");
                    sbObjScript.Append("<param name=\"src\" value=\"SoundFiles/" + fileName + "\">\r\n");
                    sbObjScript.Append("<param name=\"autoplay\" value=\"false\">\r\n");
                    sbObjScript.Append("<param name=\"controller\" value=\"false\">\r\n");
                    sbObjScript.Append("<embed src=\"SoundFiles/" + fileName + "\"");
                    sbObjScript.Append("autoplay=\"false\" controller=\"false\"");
                    sbObjScript.Append("pluginspage=\"http://www.apple.com/quicktime/download/\">\r\n");
                    sbObjScript.Append("</embed>\r\n</object>\r\n");
                    if (amount == 1)
                        timeDelay += fileNames.Length*200;
                }
                sbScript.Append(GetPlayTheSpeechFileScript(fileName, ref timeIntev, playerTypeName, timeDelay));
                amount++;
            }
            if (amount > 0)
                sbScript.Append("\r\nsetInterval(function(){clearInterval(sh" + (amount - 1) + ");}," + timeIntev + ");\r\n");
            sbScript.Append("</script>");
            
            Page.RegisterStartupScript("PageSpeechPlay", sbObjScript + sbScript.ToString());
        }

        protected void btnPlaySound_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(BAES_DIR_PATH)) return;
            string[] fs = Directory.GetFiles(BAES_DIR_PATH,"*.mp3",SearchOption.TopDirectoryOnly);
            if (fs.Length == 0) return;
            
            SetSpeechByScript(fs,rblPlayMode.SelectedValue);
            
            
        }
    }
}